package com.lancoo.znbkxx.teacher.ui.fragment

import android.graphics.drawable.AnimationDrawable
import android.os.Bundle
import android.os.Environment
import android.view.View
import android.widget.ImageView
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.android.tu.loadingdialog.LoadingDialog
import com.chad.library.adapter.base.BaseQuickAdapter
import com.lancoo.znbkxx.teacher.Ext
import com.lancoo.znbkxx.teacher.R
import com.lancoo.znbkxx.teacher.adapter.AnswerDetailAdapter
import com.lancoo.znbkxx.teacher.adapter.AnswerListAdapter
import com.lancoo.znbkxx.teacher.adapter.StuImageAdapter
import com.lancoo.znbkxx.teacher.aibkTestCoach.aibkTools.MyToast
import com.lancoo.znbkxx.teacher.aibkTestCoach.auidoPlayer.AudioTracker
import com.lancoo.znbkxx.teacher.base.BaseVMFragment
import com.lancoo.znbkxx.teacher.databinding.FmtAnswerDetailBinding
import com.lancoo.znbkxx.teacher.model.data.AnswerDetail
import com.lancoo.znbkxx.teacher.utils.GlideEngine
import com.lancoo.znbkxx.teacher.viewmodel.HardSolutionViewModel
import com.luck.picture.lib.PictureSelector

import java.io.File

/**
 * @author : wealive
 * @date   : 2020/3/20 15:55
 * @desc   :
 */
class StuAnswerDetailFragment : BaseVMFragment<HardSolutionViewModel, FmtAnswerDetailBinding>(),
        BaseQuickAdapter.OnItemClickListener, AnswerListAdapter.OnAudioClickListener {
    private val answerDetailList = mutableListOf<AnswerDetail>()
    private val quesID by lazy { requireArguments().getString("quesID") }
    lateinit var adapter: AnswerDetailAdapter
    private val audioTracker by lazy { AudioTracker() }
    lateinit var ivAudio: ImageView
    private val loadingDialog by lazy {
        LoadingDialog.Builder(requireContext()).setMessage("下载音频中...").setCancelOutside(false)
                .setCancelable(false).create()
    }

    override fun setLayoutID(): Int {
        return R.layout.fmt_answer_detail
    }

    override fun providerVMClass(): Class<HardSolutionViewModel>? {
        return HardSolutionViewModel::class.java
    }

    override fun providerContext(): Any? {
        return this
    }

    companion object {
        private const val QUESID = "quesID"
        fun newInstance(quesID: String): StuAnswerDetailFragment {
            val fragment = StuAnswerDetailFragment()
            val bundle = Bundle()
            bundle.putString(QUESID, quesID)
            fragment.arguments = bundle
            return fragment
        }
    }

    override fun onStart() {
        super.onStart()
        viewModel.getStuAnswerList(quesID!!)
    }

    override fun initView() {
        adapter = AnswerDetailAdapter( this, R.layout.item_stuanswer_detail, answerDetailList)
        adapter.onItemClickListener = this
        binding.rv.layoutManager = LinearLayoutManager(context)
        binding.rv.adapter = adapter
    }

    override fun startObserve() {
        viewModel.answerDetail.observe(this, Observer {
            answerDetailList.clear()
            answerDetailList.addAll(it)
            adapter.setNewData(answerDetailList)
        })
        viewModel.audioPath.observe(this, Observer {
            loadingDialog.dismiss()
            audioTracker.setMFilePath(it)
            audioTracker.start()
        })
    }


    override fun onItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
        if (adapter is StuImageAdapter) {
            PictureSelector.create(this).themeStyle(R.style.picture_default_style)
                    .imageEngine(GlideEngine.createGlideEngine())
                    .openExternalPreview(position, adapter.data)
        }
    }


    private fun playAudio(path: String, view: ImageView) {
        if (!this::ivAudio.isInitialized) {
            ivAudio = view
        } else {
            val drawable = ivAudio.drawable as? AnimationDrawable
            if (drawable != null && drawable.isRunning) {
                drawable.stop()
                drawable.selectDrawable(0)
                ivAudio.clearAnimation()
                ivAudio.setImageResource(R.mipmap.laba3)
            }
            ivAudio = view
        }
        lifecycle.addObserver(audioTracker)
        audioTracker.createAudioTrack()
        audioTracker.setImageView(ivAudio)
        val url = Ext.OBSINFO?.ServerWithBucket + path
        audioTracker.setPlayListener(object : AudioTracker.PlayListener {
            override fun playStart() {

            }

            override fun playPrepare() {
                requireActivity().runOnUiThread {  MyToast.showToast("音频正在加载中...") }
            }

            override fun playFinish() {
            }

        })
        val fileName = url.substring(url.lastIndexOf("/") + 1)
        val filePath = Environment.getExternalStorageDirectory()
                .absolutePath + "/Android/data/com.lancoo.znbkxx.teacher/files/audio/" + fileName
        if (File(filePath).exists()) {
            audioTracker.setMFilePath(filePath)
            audioTracker.start()
        } else {
            loadingDialog.show()
            viewModel.downLoadAudio(url, fileName)
        }
    }

    override fun success(view: ImageView, index: Int, position: Int) {
        var path =
                answerDetailList[index].AnswerList[0].AudioPath
        if (path.isEmpty()) {
            path = answerDetailList[index].AnswerList[0].ItemList[0].AudioPath
        }
        playAudio(path, view)
    }
}